<template>
  <div v-loading="loadState">
    <el-button
      @click="isUploading = true"
      type="primary"
      plain
      icon="el-icon-upload"
      >上传视频文件</el-button
    >
    <div class="video-area">
      <el-row class="row" v-for="row in rows" :key="row" :gutter="gutter">
        <el-col :span="Math.floor(24 / cols)" v-for="col in cols" :key="col">
          <video-card
            v-if="toIndex(row, col) < videoList.length"
            :thumbnail-src="
              $http.defaults.baseURL +
              thumbnailUrl +
              videoList[toIndex(row, col)].id +
              (videoList[toIndex(row, col)].state === VideoStates.PROCESSING
                ? '?process'
                : '')
            "
            v-bind="videoList[toIndex(row, col)]"
            @play="play(videoList[toIndex(row, col)])"
            @more="$refs.editor.$emit('open', videoList[toIndex(row, col)])"
          ></video-card>
        </el-col>
      </el-row>
    </div>
    <el-row type="flex" justify="end">
      <el-pagination
        layout="total, sizes, prev, pager, next, jumper"
        :current-page.sync="currentPage"
        :total="videoList.length"
        :page-size="pageSize"
      ></el-pagination>
    </el-row>
    <el-dialog title="上传视频文件" :visible.sync="isUploading" width="30%">
      <!-- <el-upload
        class="upload-demo"
        ref="upload"
        :action="action"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :file-list="fileList"
        :auto-upload="true"
        name="file"
      >
        <el-button slot="trigger" size="small" type="primary"
          >选取文件</el-button
        >
        <el-button
          style="margin-left: 10px"
          size="small"
          type="success"
          @click="submitUpload"
          >上传文件</el-button
        >
      </el-upload> -->
      <el-upload
        ref="upload"
        action="#"
        :file-list="fileUploadList"
        :auto-upload="false"
        :http-request="uploadMethod"
        :before-remove="beforeRemove"
        :on-remove="onRemove"
        :with-credentials="true"
        :on-success="onSuccess"
        :on-error="onError"
        multiple
      >
        <el-button
          slot="trigger"
          class="file-input-btn"
          size="small"
          type="primary"
          >选取文件</el-button
        >
        <el-button
          style="margin-left: 10px"
          size="small"
          type="success"
          @click="uploadFiles"
          >上传</el-button
        >
      </el-upload>
    </el-dialog>
    <el-dialog
      v-if="preview.currentVideo"
      :visible.sync="preview.isPreviewing"
      width="50%"
      @close="previewClose"
    >
      <video
        ref="video"
        class="video"
        :src="$http.defaults.baseURL + previewUrl + preview.currentVideo.id"
        controls
        autoplay
      >
        您的浏览器暂时不支持在线预览。
      </video>
    </el-dialog>
    <video-editor
      ref="editor"
      @delete-success="loadVideos"
      @change-success="loadVideos"
    ></video-editor>
  </div>
</template>

<script>
import VideoCard from "../../file-list/video-list/VideoCard";
import { getEnterpriseDetails } from "../../interface/info/EnterpriseInfo";
import VideoStates from "../../file-list/video-list/VideoStates";
// import FileUpload from "~/components/file-list/FileUpload";
import VideoEditor from "../../file-list/video-list/VideoEditor";
import { BACKEND_ROOT } from "../../../Constants";
export default {
  name: "VideoList",
  components: {
    VideoEditor,
    // FileUpload,
    VideoCard,
  },
  props: {
    uploadMethod: Function,
    onSuccess: Function,
    loadRootUrl: {
      type: String,
      required: true,
    },
    rows: {
      type: Number,
      default: 2,
    },
    cols: {
      type: Number,
      default: 4,
    },
    gutter: {
      type: Number,
      default: 10,
    },
    thumbnailUrl: {
      type: String,
      default: "/group/video/thumbnail/",
    },
    listDirectoryUrl: {
      type: String,
      default: "/group/video/ls",
    },
    uploadUrl: {
      type: String,
      default: "/group/video/upload",
    },
    previewUrl: {
      type: String,
      default: "/group/video/preview/",
    },
  },
  data() {
    return {
      videoList: [],
      currentPage: 1,
      rootDir: null,
      loadState: true,
      VideoStates,
      reloadTimeout: null,
      preview: {
        isPreviewing: false,
        currentVideo: null,
      },
      // 上传文件
      isUploading: false,
      fileUploadList: [],
      action: "",
      file: "",
    };
  },
  created() {
    this.getDirectory();
  },
  methods: {
    getDirectory() {
      axios({
        method: "get",
        url: "/group/file/directory/" + `case-video` + `?unitId=0`,
      }).then((res) => {
        // this.id = sessionStorage.setItem("id", res.data.parameter.id);
        // this.getFileList();
        console.log(res);
      });
    },
    uploadFiles() {
      this.$refs.upload.submit();
    },
    onRemove(file) {
      if (file.raw.cancelSource) {
        file.raw.cancelSource.cancel();
      }
    },
    beforeRemove(file) {
      if (file.status !== "uploading") return true;
      return new Promise((resolve, reject) => {
        this.$confirm(`文件${file.name}正在上传中，是否要取消上传？`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            resolve();
          })
          .catch(() => {
            reject();
          });
      });
    },
    onError(err, file) {
      let e = err;
      if (err.response && err.response.data) e = err.response.data;
      this.$notify.error({
        title: `${file.name}上传失败！`,
        message: e.message,
      });
    },
    toIndex(row, col) {
      return (
        (this.currentPage - 1) * this.pageSize + (row - 1) * this.cols + col - 1
      );
    },
    responseAssert(response) {
      if (
        typeof response.data.resultCode !== "string" ||
        !response.data.resultCode.startsWith("2")
      )
        throw Error(response.message);
    },
    async loadRootMeta() {
      try {
        // const unitId = (await getEnterpriseDetails()).id;
        const response = await this.$http.get(this.loadRootUrl, {
          params: { unitId: 0 },
        });
        debugger;
        this.responseAssert(response);
        return response.data.parameter;
      } catch (e) {
        console.log(e);
        let err = e;
        if (err.response && err.response.hasOwnProperty("data"))
          err = err.response.data;
        throw e;
      }
    },
    async loadList(id) {
      try {
        const response = await this.$http.get(this.listDirectoryUrl, {
          params: { id: id },
        });
        this.responseAssert(response);
        return response.data.parameter;
      } catch (e) {
        console.log(e);
        let err = e;
        if (err.response && err.response.hasOwnProperty("data"))
          err = err.response.data;
        throw e;
      }
    },
    async init() {
      try {
        this.rootDir = await this.loadRootMeta();
      } catch (e) {
        this.$alert(e.message, "加载失败", { type: "error" });
        throw e;
      }
      this.loadVideos();
    },
    async loadVideos() {
      clearTimeout(this.reloadTimeout);
      try {
        this.videoList = (await this.loadList(this.rootDir.id)).array;
        this.stateCheck();
      } catch (e) {
        this.$alert(e.message, "加载失败", { type: "error" });
        this.reloadLater();
      }
    },
    stateCheck() {
      const needFresh = this.videoList.some(
        (video) =>
          video.state === VideoStates.PROCESSING ||
          video.state === VideoStates.ENCODING
      );
      if (needFresh) this.reloadLater();
    },
    reloadLater() {
      const that = this;
      const timeout = setTimeout(() => that.loadVideos(), 10000);
      this.reloadTimeout = timeout;
      this.$on("update:beforeDestroy", () => clearTimeout(timeout));
    },
    // async uploadMethod(file, parentDir = this.rootDir) {
    //   let formData = new FormData();
    //   formData.append("file", file.file);
    //   formData.append("parentId", parentDir.id);
    //   let source = this.$http.CancelToken.source();
    //   file.file.cancelSource = source;
    //   this.$http({
    //     url: this.uploadUrl,
    //     method: "post",
    //     data: formData,
    //     //上传进度
    //     onUploadProgress: (progressEvent) => {
    //       let num = ((progressEvent.loaded / progressEvent.total) * 100) | 0; //百分比
    //       file.onProgress({ percent: num }); //进度条
    //     },
    //     cancelToken: source.token,
    //     timeout: -1,
    //   })
    //     .then((data) => {
    //       file.onSuccess(data); //上传成功(打钩的小图标)
    //     })
    //     .catch((err) => {
    //       file.onError(err);
    //     });
    // },
    // 上传文件
    submitUpload() {
      this.$refs.upload.submit();
      this.isUploading = false;
      this.getDirectory();
    },
    handlePreview(file) {
      console.log(file);
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    play(video) {
      this.preview.currentVideo = video;
      this.preview.isPreviewing = true;
    },
    previewClose() {
      this.$refs.video.pause();
    },
  },
  computed: {
    pageSize() {
      return this.rows * this.cols;
    },
  },
  mounted() {
    this.loadState = true;
    this.init().finally(() => (this.loadState = false));
    this.action =
      `${BACKEND_ROOT}/group/video/upload?parentId=` +
      sessionStorage.getItem("id");
  },
};
</script>

<style scoped>
.row {
  margin-bottom: 5px;
}
.video {
  width: 100%;
}
.video-area {
  margin-top: 5px;
  height: 90%;
}
</style>
